let querystring=require("querystring");
let http=require("http");

function request(path,method,obj) {
  
    let promise=new Promise(function (resolve,reject) {

        const postData = querystring.stringify(obj);
        const options = {
          path: path,
          port:9999,
          method: method,
        };

        if(method.trim().toUpperCase()=="POST"){
          options.headers={
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': Buffer.byteLength(postData)
          }
        }

        const req = http.request(options, (res) => {
          // console.log(`状态码: ${res.statusCode}`);
          // console.log(`响应头: ${JSON.stringify(res.headers)}`);
          if(res.statusCode>=400){
            reject(res);
          }
          res.setEncoding('utf8');
          let content="";
          res.on('data', (chunk) => {
            content+=chunk;
            // console.log(`响应主体: ${chunk}`);
          });
          res.on('end', () => {
            resolve(content);
          });
        });
        req.on('error', (e) => {
            reject(e);
        });
        console.log(postData);
        // 写入数据到请求主体
        req.write(postData);
        req.end();
     
    });

    return promise;
}

// request("/gjpzhangwu/select_all1","GET",{})
// .then(function (data) {
//   console.log(data);
// },function (e) {
//   console.log("出错了");
// });

module.exports=request;//导出网络访问对象